package com.lzgcoding.clock.timer

import android.annotation.SuppressLint
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.lzgcoding.clock.R
import kotlinx.coroutines.delay
import kotlin.math.cos
import kotlin.math.sin

@SuppressLint("DefaultLocale")
private fun formatTime(seconds: Int): String {
    val minutes = seconds / 60
    val remainingSeconds = seconds % 60
    return String.format("%02d:%02d", minutes, remainingSeconds)
}

@Composable
fun TimerView(viewModel: TimerViewModel) {
    val uiState by viewModel.stateFlow.collectAsStateWithLifecycle()

    LaunchedEffect(uiState.isRunning) {
        if (uiState.isRunning) {
            while (true) {
                delay(1000L)
                if (uiState.isRunning) {
                    viewModel.handleAction(TimerAction.UpdateElapsedSeconds)
                } else {
                    break
                }
            }
        }
    }

    val dialGrayColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
    val dialAccentColor = MaterialTheme.colorScheme.error

    TimerScreenContent(
        seconds = uiState.elapsedSeconds % 60,
        timeText = formatTime(uiState.elapsedSeconds),
        isRunning = uiState.isRunning,
        dialGrayColor = dialGrayColor,
        dialAccentColor = dialAccentColor,
        onAction = viewModel::handleAction
    )
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TimerScreenContent(
    seconds: Int,
    timeText: String,
    isRunning: Boolean,
    dialGrayColor: Color,
    dialAccentColor: Color,
    onAction: (TimerAction) -> Unit,
) {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier.size(200.dp)
        ) {
            ClockDial(
                seconds = seconds,
                modifier = Modifier.size(200.dp),
                grayColor = dialGrayColor,
                accentColor = dialAccentColor
            )
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = timeText,
                    fontSize = 32.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onSurface
                )
            }
            Text(
                text = stringResource(id = R.string.minute),
                fontSize = 12.sp,
                color = MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.padding(top = 50.dp)
            )

        }

        Button(
            onClick = {
                if (isRunning) {
                    onAction(TimerAction.Cancel)
                } else {
                    onAction(TimerAction.Start)
                }
            },
            modifier = Modifier.padding(top = 32.dp)
        ) {
            Text(
                text = if (isRunning) stringResource(id = R.string.cancel) else stringResource(id = R.string.start),
                fontSize = 18.sp
            )
        }
    }
}

@Composable
private fun ClockDial(
    seconds: Int,
    modifier: Modifier,
    grayColor: Color,
    accentColor: Color
) {
    Canvas(modifier = modifier) {
        val center = size.minDimension / 2.0f
        val outerRadius = center - 6.dp.toPx()
        val innerRadius = center - 30.dp.toPx()

        for (i in 0 until 60) {
            val angleInDegrees = 6.0 * i - 90.0
            val angleInRadians = angleInDegrees * Math.PI / 180.0

            val color = if (i < seconds) accentColor else grayColor

            val startX = (center + innerRadius * cos(angleInRadians)).toFloat()
            val startY = (center + innerRadius * sin(angleInRadians)).toFloat()
            val endX = (center + outerRadius * cos(angleInRadians)).toFloat()
            val endY = (center + outerRadius * sin(angleInRadians)).toFloat()

            drawLine(
                color = color,
                start = Offset(startX, startY),
                end = Offset(endX, endY),
                strokeWidth = 3.dp.toPx(),
                cap = StrokeCap.Round
            )
        }
    }
}